package o2o.web.actions.user.browse;

import com.jinyou.utils.common.AjaxResult;
import com.jinyou.utils.common.JYPageUtils;
import com.jinyou.utils.common.ObjectUtils;
import com.jinyou.utils.common.ValidateUtil;
import o2o.cache.shop.ShopExtraInfoMemory;
import o2o.cache.shop.ShopMemory;
import o2o.cache.shop.ShopTypeRelationMemory;

import o2o.cache.user.UserInfoMemory;
import o2o.cache.user.UserOnlineImpl;
import o2o.config.dao.UserDaoSql;
import o2o.dao.PO.PojoTables;
import o2o.company.model.ShopInfo;
import o2o.dao.PO.shop.ShopInfoExtra;
import o2o.dao.PO.shop.ShopTip;
import o2o.dao.PO.user.UserInfo;
import o2o.dao.PO.user.browse.BROWSE_HISTORY_TYPE;
import o2o.dao.PO.user.browse.UserBrowseHistory;
import o2o.dao.VO.shop.ShopInfoAndGameVO;
import o2o.dao.VO.shop.ShopTypeInfoVO;
import o2o.dao.VO.user.browse.UserBrowseHistoryVO;
import o2o.utils.CommonUtils;
import o2o.web.actions.shop.ShopTipMan;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Classname UserBrowseHistory
 * @Description 用户浏览历史模块
 * @Date 2019/4/27 11:35
 * @Created by yangtk
 */
@RestController
public class UserBrowseHistoryAction {

    @Autowired
    private UserBrowseHistoryService userBrowseHistoryService;

    // 用户浏览记录
    @RequestMapping(value = "/browse/history/list", method = RequestMethod.POST)
    public String browse_history_list(String token, Integer type, Integer page, Integer size) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (type == null) {
            type = BROWSE_HISTORY_TYPE.BROWSE_HISTORY_TYPE_SHOP;
        }
        if (page == null || page < 1) {
            page = 1;
        }
        if (size == null) {
            size = 20;
        }
        StringBuilder sql = new StringBuilder();
        sql.append(" select *  from ").append(PojoTables.USER_BROWSE_HISTORY)
                .append(" where userId =").append(user.getId()).append(" and type =").append(type)
                .append(" and delFlag = 0 order by updateTime desc");
        List<UserBrowseHistory> list = null;
        try {
            list = (List<UserBrowseHistory>) UserDaoSql.getInstance().list(UserBrowseHistory.class, sql.toString());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult("获取失败,请稍后重试");
        }
        if (ValidateUtil.isAbsList(list)) {
            // 排序
            list.stream().sorted(Comparator.comparing(UserBrowseHistory::getUpdateTime).reversed()).collect(Collectors.toList());
            list = getShopInfoList(list);
            if (ValidateUtil.isAbsList(list)) {
                JYPageUtils.PageList pageList = JYPageUtils.getList(list, page, size);
                List<UserBrowseHistoryVO> resultList = toUserBrowseHistoryVOList((List<UserBrowseHistory>) pageList.list);
                if (ValidateUtil.isAbsList(resultList)) {
                    return AjaxResult.successResult(pageList.totalCount, resultList.size(), resultList);
                }
            }
        }
        return AjaxResult.successResult(0, 0, null);
    }

    private List<UserBrowseHistoryVO> toUserBrowseHistoryVOList(List<UserBrowseHistory> list) {

        if (ValidateUtil.isAbsList(list)) {
            List<UserBrowseHistoryVO> tempList = new ArrayList<>();
            for (UserBrowseHistory userBrowseHistory : list) {
                UserBrowseHistoryVO userBrowseHistoryVO = toUserBrowseHistoryVO(userBrowseHistory);
                if (userBrowseHistoryVO != null) {
                    tempList.add(userBrowseHistoryVO);
                }
            }
            if (ValidateUtil.isAbsList(tempList)) {
                return tempList;
            }
        }
        return null;
    }

    private List<UserBrowseHistory> getShopInfoList(List<UserBrowseHistory> list) {
        if (ValidateUtil.isAbsList(list)) {
            List<UserBrowseHistory> effectiveList = new ArrayList<>();
            for (UserBrowseHistory userBrowseHistory : list) {
                if (userBrowseHistory == null) {
                    continue;
                }
                if (ValidateUtil.isNotID(userBrowseHistory.getShopId())) {
                    continue;
                }
                ShopInfo shopInfo = ShopMemory.getInstance().getShopById(userBrowseHistory.getShopId());
                if (shopInfo == null) {
                    continue;
                }
                effectiveList.add(userBrowseHistory);
            }
            if (ValidateUtil.isAbsList(effectiveList)) {
                return effectiveList;
            }
        }
        return null;
    }

    // 获取一个
    private UserBrowseHistoryVO toUserBrowseHistoryVO(UserBrowseHistory history) {
        if (history == null) {
            return null;
        }
        UserBrowseHistoryVO userBrowseHistoryVO = new UserBrowseHistoryVO();
        try {
            ObjectUtils.copyPropertiesExclude(history, userBrowseHistoryVO);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (userBrowseHistoryVO != null) {
            ShopInfoAndGameVO shopInfoAndGameVO = getShopDetailOne(userBrowseHistoryVO.getShopId());
            if (shopInfoAndGameVO != null) {
                userBrowseHistoryVO.setShopInfoAndGameVO(shopInfoAndGameVO);
            }
            return userBrowseHistoryVO;
        }
        return null;
    }

    //获取某一店铺的详细信息
    private ShopInfoAndGameVO getShopDetailOne(Long shopId) {
        try {
            if (ValidateUtil.isNotID(shopId)) {
                return null;
            }
            ShopInfo info = ShopMemory.getInstance().getShopById(shopId);
            if (null == info) {
                return null;
            }
            List<ShopTypeInfoVO> typeInfoVOList = new ArrayList<ShopTypeInfoVO>();

            //获取店铺所属行业
            List<Integer> list = ShopTypeRelationMemory.getInstance().shopTypeList(info.getId());
            if (ValidateUtil.isAbsList(list)) {
                for (int i = 0; i < list.size(); i++) {
                    if (null == list.get(i)) {
                        continue;
                    }


                }
            }

            ShopInfoAndGameVO infoVO = new ShopInfoAndGameVO();
            try {
                ObjectUtils.copyPropertiesExclude(info, infoVO);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
            //店铺所属行业
            infoVO.setShopType(typeInfoVOList);

//            //获取店铺所属行业
//            List<RegionInfoVO> relationList = ShopMan.getRegionListOfShop(infoVO.getId());
//            if (ValidateUtil.isAbsList(relationList)) {
//                infoVO.setRegions(relationList);
//            }

            //获取店铺评分、星级、销量
            ShopInfoExtra extraInfo = ShopExtraInfoMemory.getInstance().getShopExtraInfoById(info.getId());
            if (null != extraInfo) {
                infoVO.setStar(extraInfo.getStar());
                infoVO.setScore(extraInfo.getScore());
                infoVO.setOrderCounts(extraInfo.getOrderCounts());
                infoVO.setMonthOrderCount(extraInfo.getMonthOrderCount());
                infoVO.setShowOrderCounts(extraInfo.getShowOrderCounts());
            }
            //店铺标签
            List<ShopTip> tipList = ShopTipMan.tipListOfShopId(info.getId());
            if (ValidateUtil.isAbsList(tipList)) {
                infoVO.setShopTipList(tipList);
            }
            return infoVO;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    // 删除指定的浏览记录
    @RequestMapping(value = "/browse/history/del")
    public String browse_history_del(String token, String ids) {
        UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (userInfo == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (ValidateUtil.isNull(ids)) {
            return AjaxResult.successResult();
        }
        Set<Long> set = CommonUtils.splitToSet(ids, Long.class);
        if (set == null || set.isEmpty()) {
            return AjaxResult.successResult();
        }
        StringBuilder sql = new StringBuilder();
        sql.append(" update ").append(PojoTables.USER_BROWSE_HISTORY)
                .append(" set delFlag = 1").append(" where id in (").append(StringUtils.join(set, ",")).append(") ");
        try {
            UserDaoSql.getInstance().executeBySql(sql.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        userBrowseHistoryService.cleanCache(userInfo.getId());
        return AjaxResult.successResult();
    }
}
